#include "route.h"
RouteStruct* route_links[ROUTES_NUM_MAX];
uint16_t route_len = 0;

RouteStruct* route_new(LinkCfgStruct* link) {
  RouteStruct* self;
  self = (RouteStruct*)mempool_alloc(sizeof(RouteStruct));
  self->id = (uint8_t*)mempool_alloc(8);
  if (link->status == linkStatus_temp) {
    self->link = link_new(link);
  } else {
    self->link = link;
  }

  return self;
}
void route_del(RouteStruct* self) {
  mempool_free(self->id);
  if (self->link->status == linkStatus_temp) {
    link_del(self->link);
  }
  mempool_free(self);
}

int16_t route_update(uint8_t* id, LinkCfgStruct* link) {
  for (uint16_t i = 0; i < route_len; i++) {
    if (mem_cmp(route_links[i]->id, id, 8) == 0) {
      if (route_links[i]->link->status == linkStatus_temp) {
        link_del(route_links[i]->link);

        mem_cpy(route_links[i]->id, id, 8);
        if (link->status == linkStatus_temp) {
          route_links[i]->link = link_new(link);
        } else {
          route_links[i]->link = link;
        }
        return i;
      } else {
        return -1;
      }
    }
  }

  if (route_len < ROUTES_NUM_MAX) {
    RouteStruct* route = route_new(link);
    mem_cpy(route->id, id, 8);
    route_links[route_len] = route;
    return route_len++;
  }
  return -2;
}
void route_fix(uint8_t* id) {
  for (uint16_t i = 0; i < route_len; i++) {
    if (mem_cmp(route_links[i]->id, id, 8) == 0) {
      if (route_links[i]->link->status == linkStatus_temp) {
        route_links[i]->link->status = linkStatus_fixed;
      }
    }
  }
}
void route_remove(uint8_t* id) {
  for (uint16_t i = 0; i < route_len; i++) {
    if (mem_cmp(route_links[i]->id, id, 8) == 0) {
      route_del(route_links[i]);
      route_links[i] = route_links[--route_len];
    }
  }
}
RouteStruct* route_find(uint8_t* id) {
  for (uint16_t i = 0; i < route_len; i++) {
    if (mem_cmp(route_links[i]->id, id, 8) == 0) {
      return route_links[i];
    }
  }
  return NULL;
}
